using System;
using System.Collections.Generic;
using System.Linq;
using SiemensAmd.Mmt.McisDbModel;
using SqlSugar;
using SqlSugarEx.Utilities;

namespace SiemensAmd.Mmt.McisDbDal
{
	public class TdiToolMasterDataDal
	{
		private readonly SqlSugarClient _sqlSugar;

		public TdiToolMasterDataDal(string server, string db, string user, string pwd)
		{
			this._sqlSugar = new SqlSugarClient(new ConnectionConfig
			{
				DbType = DbType.SqlServer,
				ConnectionString = DbUtility.SQLDbFormat(server, db, user, pwd),
				IsAutoCloseConnection = false
			});
		}

		public List<TDI_TOOL_MASTERDATAEntity> QueryMasterData(string toolIdentify = "")
		{
			return this._sqlSugar.Queryable<TDI_TOOL_MASTERDATAEntity>().WhereIF(!string.IsNullOrWhiteSpace(toolIdentify), (TDI_TOOL_MASTERDATAEntity x) => x.TOOLID == toolIdentify).ToList();
		}

		public List<TDI_TOOL_MASTERDATAEntity> QueryMasterData(string toolIdentify, int toolType)
		{
			return (from x in this._sqlSugar.Queryable<TDI_TOOL_MASTERDATAEntity>()
				where x.TOOLID == toolIdentify
				where x.TOOLTYP == toolType
				select x).ToList();
		}

		public virtual bool InsertUserData(string toolIdentify, int toolType, string userDataFormat, UserDataEntity entity)
		{
			List<TDI_TOOL_MASTERDATAEntity> list = this.QueryMasterData(toolIdentify, toolType);
			if (list.Count == 0)
			{
				throw new Exception("刀具主数据不存在！");
			}
			List<TDI_TOOL_MASTERDATAEntity> list2 = list.Where((TDI_TOOL_MASTERDATAEntity x) => x.TOOLDATATYP == 2 && !string.IsNullOrWhiteSpace(x.TOOLDATAFORMAT)).ToList();
			try
			{
				this._sqlSugar.Ado.BeginTran();
				if (list2.Count > 0)
				{
					this._sqlSugar.Deleteable(list2).ExecuteCommand();
				}
				TDI_TOOL_MASTERDATAEntity insertObj = new TDI_TOOL_MASTERDATAEntity
				{
					TOOLID = toolIdentify,
					TOOLDATAFORMAT = userDataFormat,
					TOOLDATA = BodyBuild.CreateUserData(userDataFormat, entity),
					TOOLTYP = toolType,
					TOOLDATATYP = 2,
					TOOLTEXT = "0"
				};
				bool result = this._sqlSugar.Insertable(insertObj).InsertColumns((TDI_TOOL_MASTERDATAEntity x) => new { x.TOOLID, x.TOOLDATAFORMAT, x.TOOLDATA, x.TOOLDATATYP, x.TOOLTEXT, x.TOOLTYP }).ExecuteCommand() > 0;
				this._sqlSugar.Ado.CommitTran();
				return result;
			}
			catch (Exception innerException)
			{
				this._sqlSugar.Ado.RollbackTran();
				throw new Exception("操作失败！", innerException);
			}
		}
	}
}
